<?php

namespace App\Jobs\Articles;

use App\Exceptions\BusinessException;
use App\Models\Article;
use App\Models\ArticlesDrafts;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class Publish implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle()
    {
        ArticlesDrafts::where('status', 0)
            ->where('publish_date', '<=', now()->format('Y-m-d H:i:s'))
            ->chunkById(500, function ($articles) {
                foreach ($articles as $draft) {

                    try {
                        DB::beginTransaction();

                        Article::create([
                            'publish_id'        => $draft->publish_id,
                            'type'              => $draft->type,
                            'title'             => $draft->title,
                            'desc'              => $draft->desc,
                            'file_type'         => $draft->file_type,
                            'files'             => $draft->files,
                            'video'             => $draft->video,
                            'thum_img'          => $draft->thum_img,
                            'content'           => $draft->content,
                            'is_hot'            => $draft->is_hot,
                            'is_top'            => $draft->is_top,
                            'first_relay_count' => $draft->first_relay_count,
                            'first_fav_count'   => $draft->first_fav_count,
                            'tag_id'            => $draft->tag_id,
                            'mini_type'         => $draft->mini_type,
                        ]);

                        $draft->update(['status' => 1]);

                        DB::commit();
                    } catch (\Throwable $e) {
                        DB::rollBack();

                        log_exception('定时发布文章异常', $e);

                        throw new BusinessException('发布文章异常');
                    }
                }
            });
    }
}
